package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.adapter.VpCommonAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.IndicatorManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.vp.SuperViewPager;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.PassDataInfo;
import com.ycsj.goldmedalnewconcept.common.bean.TkItemBean;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.teacher.bean.QuestionTitle;
import com.ycsj.goldmedalnewconcept.teacher.fragment.QuestionsListFragment;

import net.lucode.hackware.magicindicator.MagicIndicator;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * 教师端--添加题目
 * Created by Administrator on 2019/2/21 0021.
 */

public class TeacherAddQuestionsActivity extends BaseActivity implements ViewPager.OnPageChangeListener, CancelAdapt {
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.mag)
    MagicIndicator mag;
    @BindView(R.id.vp)
    SuperViewPager vp;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.bt_add_homework)
    Button bt_add_homework;

    //导航栏的标题
    private List<String> titles;

    //填充Vp的Framgent集合
    private List<Fragment> fragments;

    //记录Vp的选中位置
    private int vpSelectPos;

    //根据查询条件请求服务器后更新页面数据的标识
    public static final int UPDATE = 0x120;

    public static final int NUMBER = 0x121;


    //年级,题目编号
    private String grade_D, questionID;

    //题目可添加总数,用于选择题目界面进行操作
    private int questionNum;

    //记录的可添加题目总数,用于筛选条件查询后还原可添加题目总数
    private int recordTotalNum;

    //添加的题目数据集合,
    private List<TkItemBean> addQuestionInfo;

    /**
     * 给Framgent提供获取可添加题目总数的方法
     *
     * @return
     */
    public int getQuestionNum() {
        return questionNum;
    }

    public void setQuestionNum(int questionNum) {
        this.questionNum = questionNum;
    }

    public List<TkItemBean> getAddQuestionInfo() {
        return addQuestionInfo;
    }

    /**
     * 跳转到当前页面传递的参数
     *
     * @param context
     * @param grade_D    班级
     * @param unit_D     单元号
     * @param questionID 题目编号 拼接方式:1-2_2-1
     */
    public static void goActivity(Context context, String grade_D, String unit_D, String questionID, int question_Num) {
        Intent intent = new Intent(context, TeacherAddQuestionsActivity.class);
        intent.putExtra("grade_D", grade_D);
        intent.putExtra("unit_D", unit_D);
        intent.putExtra("questionID", questionID);
        intent.putExtra("question_Num", question_Num);
        context.startActivity(intent);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_add_questions;
    }

    @Override
    protected void init() {
        //沉浸状态栏
        initStateBar();

        //获取intent数据
        initIntent();

        //请求数据
        http(grade_D, "", "", "", "", questionID);
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {
        Intent intent = getIntent();
        grade_D = intent.getStringExtra("grade_D");
        questionID = intent.getStringExtra("questionID");
        questionNum = intent.getIntExtra("question_Num", -1);
        recordTotalNum = intent.getIntExtra("question_Num", -1);
        //初始化可添加的题目数量
        addQuestionInfo = new ArrayList<>();

    }

    /**
     * @param grade_D        年级
     * @param unit_D         单元
     * @param difficulty     难度
     * @param knowledgeAim_D 知识语言目标
     * @param knowledge      知识点
     * @param questionID     题目编号
     */
    private void http(final String grade_D, final String unit_D, final String difficulty, final String knowledgeAim_D, final String knowledge, final String questionID) {

        Map<String, String> map = new HashMap<>();

        map.put("type", "9");

        if (TextUtils.isEmpty(grade_D)) {
            map.put("grade_D", "");
        } else {
            map.put("grade_D", grade_D);
        }

        if (TextUtils.isEmpty(unit_D)) {
            map.put("unit_D", "");
        } else {
            map.put("unit_D", unit_D);
        }

        if (TextUtils.isEmpty(difficulty)) {
            map.put("difficulty", "");
        } else {
            map.put("difficulty", difficulty);
        }

        if (TextUtils.isEmpty(knowledgeAim_D)) {
            map.put("knowledgeAim_D", "");
        } else {
            map.put("knowledgeAim_D", knowledgeAim_D);
        }

        if (TextUtils.isEmpty(knowledge)) {
            map.put("knowledge", "");
        } else {
            map.put("knowledge", knowledge);
        }

        if (TextUtils.isEmpty(questionID)) {
            map.put("questionID", "");
        } else {
            map.put("questionID", questionID);
        }
//        Log.i("test",HttpAddress.QUESTIONTITLE+"?"+"type=9&"+"unit_D"+unit_D+"");

        HttpUtils.post(HttpAddress.QUESTIONTITLE, map, this, new HttpCallBack<QuestionTitle>() {
            @Override
            public void onSuccess(QuestionTitle info) {
                if ("200".equals(info.getState())) {

                    lvEdit.setVisibility(View.VISIBLE);
                    //返回成功
                    List<QuestionTitle.DataBean> titleDatas = info.getData();
                    if (null != titleDatas && titleDatas.size() != 0) {
                        //证明有导航栏数据
                        titles = new ArrayList<>();
                        fragments = new ArrayList<>();
                        for (int i = 0; i < titleDatas.size(); i++) {
                            if (titleDatas.get(i).getAmount() != -1) {
                                //题目id
                                int id = titleDatas.get(i).getId();
                                //题目数量
                                int num = titleDatas.get(i).getAmount();

                                //返回的该题目类型有数据
                                switch (id) {
                                    case 1:
                                        //阅读理解(判断题)
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 2:
                                        //阅读理解(填空题)
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 3:
                                        //阅读理解(选择题)
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 4:
                                        //阅读理解(问答题)
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 5:
                                        //完型填空
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 6:
                                        //填空题
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 7:
                                        //根据所给词适当形式填空
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 8:
                                        //
                                        break;
                                    case 9:
                                        //翻译
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                    case 10:
                                        //单项选择
                                        titles.add(getTitle(info.getData().get(i).getName(), "", num + ""));
                                        break;
                                }

                                fragments.add(QuestionsListFragment.newInstance(new PassDataInfo(id, grade_D, unit_D, difficulty, knowledgeAim_D, knowledge, questionID)));
                            }
                        }

                        //设置导航条数据
                        initMag();

                        //初始化Vp
                        initVp();

                        //加载完成后设置
                        if (rlLoading.getVisibility() != View.GONE) {
                            rlLoading.setVisibility(View.GONE);
                        }

                        if (rlContent.getVisibility() != View.VISIBLE) {
                            rlContent.setVisibility(View.VISIBLE);
                        }

                    } else {
                        //加载完成后设置
                        if (rlLoading.getVisibility() != View.GONE) {
                            rlLoading.setVisibility(View.GONE);
                        }

                        ToastUtils.showShort("暂无可添加的题目");

                    }

                } else {
                    //返回其它状态码
                    ToastUtils.showShort(BaseApplication.STATEERROE + info.getState());
                }


            }

            @Override
            public void onError(String e) {
                if (rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });

    }

    /**
     * 设置导航条的数据
     */
    private void initMag() {
        IndicatorManager.setIndicator(this, mag, vp, titles, getResources().getColor(R.color.tab_normal), getResources().getColor(R.color.tab_select));
    }

    /**
     * 初始化ViewPager
     */
    private void initVp() {
        VpCommonAdapter adapter = new VpCommonAdapter(getSupportFragmentManager(), fragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(fragments.size());
        vp.addOnPageChangeListener(this);
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.bt_lookhomework, R.id.bt_add_homework})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //按条件删选
                UiUtils.startActivity(this, SearchByConditionActivity.class);
                break;
            case R.id.bt_lookhomework:
                //查看我的练习

                break;
            case R.id.bt_add_homework:
                //添加至练习
                if (addQuestionInfo.size() == 0) {
                    ToastUtils.showShort("您还未添加题目");
                } else {
                    BusInfo busInfo = new BusInfo();
                    busInfo.type = TeacherTKAssignHomeworkActivity.ADDQUESTIONUPDATE;
                    busInfo.msg = GsonUtil.listToJson(addQuestionInfo);
                    EventBus.getDefault().post(busInfo);
                    //关闭当前页面
                    finish();
                }
                break;
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && UPDATE == busInfo.type) {
            //请求EventBus传递过来请求条件,这里暂时未处理查询条件
            //获取查询条件
            String grade_d = busInfo.grade_D;
            String unit_d = busInfo.unit_D;
            String knowledgeAim_d = busInfo.knowledgeAim_D;
            String knowledge = busInfo.knowledge;
            String difficulty = busInfo.difficulty;

            //刷新页面后重置添加的题目数据集合
            addQuestionInfo.clear();
            setQuestionNum(recordTotalNum);

            //还原添加至练习按钮的状态
            bt_add_homework.setBackgroundResource(R.drawable.teacher_tk_un_addquestion);
            bt_add_homework.setEnabled(false);

            //重新请求页面数据
            http(grade_d, unit_d, difficulty, knowledgeAim_d, knowledge, questionID);
        } else if (null != busInfo && NUMBER == busInfo.type) {
            //添加题目数量
            if (addQuestionInfo.size() != 0) {
                bt_add_homework.setBackgroundResource(R.drawable.add_homework);
                bt_add_homework.setEnabled(true);
            } else {
                bt_add_homework.setBackgroundResource(R.drawable.teacher_tk_un_addquestion);
                bt_add_homework.setEnabled(false);
            }
        }
    }

    /**
     * 动态将题目名称,题目类型和题目数量拼接换行后返回的方法
     */
    public String getTitle(String questionName, String questionType, String num) {
        StringBuffer sb = new StringBuffer();
        if (!questionName.isEmpty()) {
            sb.append(questionName);
        }

        if (!questionType.isEmpty()) {
            sb.append("\n");
            sb.append("(");
            sb.append(questionType);
            sb.append(")");
        }

        if (!num.isEmpty()) {
            sb.append("\n");
            sb.append("(");
            sb.append(num);
            sb.append(")");
        }

        return sb.toString();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        vpSelectPos = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
